package org.brisling.common.util;

import java.io.FileInputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.w3c.dom.Document;

/**
 * 
 * <p>Title: ConvertUtil</p>
 * <p>Description: 文档类型转换类</p>
 * <p>Company: tongking</p>
 * @author jackson wang
 * @since 1.0
 * @version 1.0
 * @date 2017年1月14日 下午10:46:34
 */
public class ConvertUtil {

	private static ConvertUtil cu;
	
	private ConvertUtil(){};
	
	/**
	 * 单例模式获取类实例
	 * @return
	 */
	public static ConvertUtil getInstances(){
		if(cu==null)
			cu = new ConvertUtil();
		return cu;
	}
	
	/**
	 * 转换word类型文档
	 * @param response  
	 * @param type		1:doc,2:docx,3:xls,4:xlsx
	 * @param pathName	文件名称
	 */
	public static String convert2Html(String pathName,String expandName){
		String ret = "";
		if( pathName!=null && pathName.trim()!=null){
			
			switch(expandName){
				
				case "doc":
					//doc类型
					try {
						ret = doc2Html(pathName);
					} catch (TransformerException | IOException | ParserConfigurationException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					break;
				case "docx":
					//docx类型
					try{
						ret = docx2Html(pathName);
					}catch(Exception e){
						e.printStackTrace();
					}
					break;
					
				case "xls":
					break;
					
				case "xlsx":
					break;
					
				default:
					break;
			}
			
		}
		
		return ret;
	}	
	
	/**
	 * 读取文件内容，进行转换并输出为html格式数据
	 * @param fileName
	 * @return
	 * @throws TransformerException
	 * @throws IOException
	 * @throws ParserConfigurationException
	 */
	private static String doc2Html(String fileName)  
            throws TransformerException, IOException,  
            ParserConfigurationException {  
        HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(fileName));//WordToHtmlUtils.loadDoc(new FileInputStream(inputFile));  
        WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(  
                DocumentBuilderFactory.newInstance().newDocumentBuilder()  
                        .newDocument());  
//         wordToHtmlConverter.setPicturesManager( new PicturesManager()  
//         {  
//             public String savePicture( byte[] content,  
//                     PictureType pictureType, String suggestedName,  
//                     float widthInches, float heightInches )  
//             {  
//                 return "test/"+suggestedName;  
//             }  
//         } );  
        wordToHtmlConverter.processDocument(wordDocument);  
        //save pictures  
//        List<Picture>  pics=wordDocument.getPicturesTable().getAllPictures();  
//        if(pics!=null){  
//            for(int i=0;i<pics.size();i++){  
//                Picture pic = (Picture)pics.get(i);  
//                System.out.println();  
//                try {  
//                    pic.writeImageContent(new FileOutputStream("D:/test/"  
//                            + pic.suggestFullFileName()));  
//                } catch (FileNotFoundException e) {  
//                    e.printStackTrace();  
//                }    
//            }  
//        }  
        Document htmlDocument = wordToHtmlConverter.getDocument();  
        ByteArrayOutputStream out = new ByteArrayOutputStream();  
        DOMSource domSource = new DOMSource(htmlDocument);  
        StreamResult streamResult = new StreamResult(out);  
  
        TransformerFactory tf = TransformerFactory.newInstance();  
        Transformer serializer = tf.newTransformer();  
        serializer.setOutputProperty(OutputKeys.ENCODING, "GBK");  
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");  
        serializer.setOutputProperty(OutputKeys.METHOD, "html");  
        serializer.transform(domSource, streamResult);  
        out.close();  
        return new String(out.toByteArray());  
    }  
	
	/**
	 * 读取2007版以后的word文件内容，进行转换并输出为html格式数据
	 * @param fileName
	 * @return
	 * @throws TransformerException
	 * @throws IOException
	 * @throws ParserConfigurationException
	 */
	private static String docx2Html(String fileName)  
            throws TransformerException, IOException,  
            ParserConfigurationException {  
        XWPFDocument wordDocument = new XWPFDocument(new FileInputStream(fileName));//WordToHtmlUtils.loadDoc(new FileInputStream(inputFile));  
        XHTMLOptions options = XHTMLOptions.create();
       
        
//        // 存放图片的文件夹
//        options.setExtractor(new FileImageExtractor(new File(imagePathStr)));
//        // html中图片的路径
//        options.URIResolver(new BasicURIResolver("image"));
        
        ByteArrayOutputStream out = new ByteArrayOutputStream(); 
        
        
        XHTMLConverter xhtmlConverter = (XHTMLConverter) XHTMLConverter.getInstance();
        xhtmlConverter.convert(wordDocument, out, options);  
         
        out.close();
  
         
        return new String(out.toByteArray());  
    } 

	
}
